const { Sequelize } = require('sequelize');

/*
* 与数据库myDb建立连接
* note：需要先创建my_db数据库
**/
const sequelize = new Sequelize('my_db', 'root', '123456', {
  dialect: 'mysql',
  host: 'localhost',
  port: '3306',
  operatorsAliases: false
})


/*
* 表-模型
**/
const UserModel = require('./model/user')(sequelize)
const BookModel = require('./model/book')(sequelize)

/*
* 表（模型）之间的关联关系
**/
// 与目标模型建立1:N关联关系
UserModel.hasMany(BookModel, { foreignKey: 'userId', targetKey: 'userId', as: 'bookList' })
// 与目标模型建立1:1关联关系
BookModel.belongsTo(UserModel, { foreignKey: 'userId', targetKey: 'userId', as: 'userInfo' })

/*
* 表-操作
**/
const User = require('./operate/user')
const Book = require('./operate/book')


module.exports = {
  userInstance: null, // user表实例
  bookInstance: null, // book表实例
  async drop () { // 删除所有表
    await sequelize.sync() // 同步所有尚未在数据库中的模型
    await sequelize.drop()
  },
  // 获取用户表实例
  getUserInstance () {
    try {
      if (!this.userInstance) {
        this.userInstance = new User(sequelize, UserModel, BookModel)
      }
      return this.userInstance
    } catch (e) {
      throw e
    }
  },
  // 获取书本实例
  getBookInstance () {
    try {
      if (!this.bookInstance) {
        this.bookInstance = new Book(sequelize, BookModel, UserModel)
      }
      return this.bookInstance
    } catch (e) {
      throw e
    }
  }
}